function varargout = searchRegistry_gui(varargin)
% SEARCHREGISTRY_GUI is the GUI for DAS Registry search in Browser
%      SEARCHREGISTRY_GUI, by itself, creates a new SEARCHREGISTRY_GUI or raises the existing
%      singleton*.
%
%      H = SEARCHREGISTRY_GUI returns the handle to a new SEARCHREGISTRY_GUI or the handle to
%      the existing singleton*.
%
%      SEARCHREGISTRY_GUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in SEARCHREGISTRY_GUI.M with the given input arguments.
%
%      SEARCHREGISTRY_GUI('Property','Value',...) creates a new SEARCHREGISTRY_GUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before searchRegistry_gui_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to searchRegistry_gui_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: DAS_GUI
% 
%    DASMiner: DAS library and browser for Matlab.
%    Diogo Veiga, March 2008.


% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @searchRegistry_gui_OpeningFcn, ...
                   'gui_OutputFcn',  @searchRegistry_gui_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before searchRegistry_gui is made visible.
function searchRegistry_gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to searchRegistry_gui (see VARARGIN)

% Choose default command line output for searchRegistry_gui
handles.output = hObject;

handles.popupmenu_Server = varargin{1};

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes searchRegistry_gui wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = searchRegistry_gui_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in radiobutton1.
function radiobutton1_Callback(hObject, eventdata, handles)
% hObject    handle to radiobutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobutton1


% --- Executes on button press in radiobutton2.
function radiobutton2_Callback(hObject, eventdata, handles)
% hObject    handle to radiobutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobutton2


% --- Executes on selection change in popupmenu_SearchCrit.
function popupmenu_SearchCrit_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu_SearchCrit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu_SearchCrit contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_SearchCrit
deleteTableResults(hObject,handles);
set(handles.popupmenu_OptionsSearch,'String','');
set(handles.popupmenu_OptionsSearch,'Visible','off');

if (get(hObject,'Value') == 2) 
    hDial = openRunningDialog(handles.figure_DASdiscovery);
    list = getDASRegistryOptions('criteria','organism');
    delete(hDial);
    clear hDial;

    if (~iscellstr(list))
        return;
    end
elseif (get(hObject,'Value') == 3) 
    hDial = openRunningDialog(handles.figure_DASdiscovery);
    list = getDASRegistryOptions('criteria','type');
    delete(hDial);
    clear hDial;

    if (~iscellstr(list))
        return;
    end
elseif (get(hObject,'Value') == 4) 
    hDial = openRunningDialog(handles.figure_DASdiscovery);
    list = getDASRegistryOptions('criteria','authority');
    delete(hDial);
    clear hDial;

    if (~iscellstr(list))
        return;
    end
    
elseif (get(hObject,'Value') == 5) 
    hDial = openRunningDialog(handles.figure_DASdiscovery);
    list = getDASRegistryOptions('criteria','capability');
    delete(hDial);
    clear hDial;

    if (~iscellstr(list))
        return;
    end

end

if ( (1 < get(hObject,'Value')) &&  (get(hObject,'Value') < 6) ) 
    set(handles.field_labelSearch,'Visible','off');
    set(handles.field_labelSearch,'String','');
    set(handles.popupmenu_OptionsSearch,'String',list);
    set(handles.popupmenu_OptionsSearch,'Visible','on');
    

elseif (get(hObject,'Value') == 6)
    set(handles.field_labelSearch,'Visible','on');
    set(handles.popupmenu_OptionsSearch,'Visible','off');
end
    set(handles.pushbutton_FindRegistry,'Visible','on');





% --- Executes during object creation, after setting all properties.
function popupmenu_SearchCrit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu_SearchCrit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in popupmenu_SearchType.
function popupmenu_SearchType_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu_SearchType (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu_SearchType contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_SearchType

deleteTableResults(hObject,handles);
if (get(hObject,'Value') == 1)
    resetSearchMenus(handles);
    deleteTableResults(hObject,handles);
elseif (get(hObject,'Value') == 2)
    resetSearchMenus(handles);
    set(handles.popupmenu_SearchCrit,'Value',1);
    set(handles.popupmenu_SearchCrit,'Visible','on');
elseif (get(hObject,'Value') == 3)
    resetSearchMenus(handles);
    set(handles.pushbutton_FindRegistry,'Visible','on');
end
    

% --- Executes during object creation, after setting all properties.
function popupmenu_SearchType_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu_SearchType (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in popupmenu_OptionsSearch.
function popupmenu_OptionsSearch_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu_OptionsSearch (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu_OptionsSearch contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu_OptionsSearch
deleteTableResults(hObject,handles);

% --- Executes during object creation, after setting all properties.
function popupmenu_OptionsSearch_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu_OptionsSearch (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbutton_FindRegistry.
function pushbutton_FindRegistry_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_FindRegistry (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

deleteTableResults(hObject,handles);
switch get(handles.popupmenu_SearchType,'Value')
    
    case 1
        resetSearchMenus;
    case 2
        
        if (get(handles.popupmenu_SearchCrit,'Value') <6)
            contents = get(handles.popupmenu_OptionsSearch,'String');
            opt = contents{get(handles.popupmenu_OptionsSearch,'Value')};
        end
        
        hDial = openRunningDialog(handles.figure_DASdiscovery);
        
        switch get(handles.popupmenu_SearchCrit,'Value')
            
            case 2 
                [xmlS, xml, status] = searchDASRegistry('organism',opt);
            case 3 
                [xmlS, xml, status] = searchDASRegistry('type',opt);
            case 4 
                [xmlS, xml, status] = searchDASRegistry('authority',opt);
            case 5 
                [xmlS, xml, status] = searchDASRegistry('capability',opt);
            case 6
                
                if (isempty(get(handles.field_labelSearch,'String')))
                    msgbox('Enter the label for the search.','Input Requested','warn');
                    return;
                else
                    [xmlS, xml, status] = searchDASRegistry('label',get(handles.field_labelSearch,'String') );
                end
                
                
        end
        delete(hDial);
        clear hDial;

        if (~checkDASResponse(xmlS,status))
            return;
        end

        tab = createTableResults(xml,handles.figure_DASdiscovery);
        
        if (~(tab == -1))
            handles.tab = tab;
            guidata(hObject,handles);
            drawResultsTable(handles);
        end
            
        
    case 3
        hDial = openRunningDialog(handles.figure_DASdiscovery);
        [xmlS, xml, status] = searchDASRegistry;
        delete(hDial);
        clear hDial;

        if (~checkDASResponse(xmlS,status))
            return;
        end
        
        tab = createTableResults(xml,handles.figure_DASdiscovery);
        
        if (~(tab == -1))
            handles.tab = tab;
            guidata(hObject,handles);
            drawResultsTable(handles);
        end
end

% --- Executes on button press in pushbutton_FindRegistry.
function pushbutton_NewSrch_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_FindRegistry (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
deleteTableResults(hObject,handles);
resetSearchMenus(handles);
set(handles.popupmenu_SearchType,'Value',1);

% --- Executes on button press in pushbutton_FindRegistry.
function pushbutton_addSource_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_addSource (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
jt = handles.tab.getTable;
row = jt.getSelectedRows;
msgDial = cell(size(row,1),1);

selection = questdlg('Do you want to add the selected DAS service(s) for browsing?',...
                     'Adding new service(s)...',...
                     'Yes','No','Yes');
switch selection,
   case 'Yes',
       tModel = handles.tab.getTableModel; %actual data
       for k=1:size(row,1)
           uri = tModel.getValueAt(row(k,1),0);
           name = tModel.getValueAt(row(k,1),1);
           [ok,msg] = addNewServer(uri,name,0);
           msgDial{k} = msg;
           if (ok), populateServerMenu(handles.popupmenu_Server); end
       end
       msgbox(msgDial ,'DAS Registry Discovery','warn');

    case 'No'
     return
end


% --- Executes on selection change in popupmenu4.
function popupmenu4_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu4 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu4


% --- Executes during object creation, after setting all properties.
function popupmenu4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function deleteTableResults(hObject,handles)

if (isfield(handles,'tab'))
    
    posWin = get(handles.figure_DASdiscovery,'Position');
    posTab = get(handles.tab,'Position');
    posPanel = get(handles.uipanel_SearchRegistry,'Position');
    delete(handles.tab);

    posWin(4) = posWin(4) - posTab(4) - 10; % new height
    set(handles.figure_DASdiscovery,'Position',posWin);
    
    handles = rmfield(handles,'tab');
    guidata(hObject,handles);
    
    myResizeFcn(handles.figure_DASdiscovery,handles); %reposition of panel
    movegui(handles.figure_DASdiscovery,'northeast');
    drawnow;
end

function resetSearchMenus(handles)

set(handles.popupmenu_OptionsSearch,'Visible','off');
set(handles.popupmenu_OptionsSearch,'Value',1);
set(handles.popupmenu_OptionsSearch,'String','');
set(handles.popupmenu_SearchCrit,'Visible','off');
set(handles.popupmenu_SearchCrit,'Value',1);

set(handles.pushbutton_FindRegistry,'Visible','off');
set(handles.field_labelSearch,'Visible','off');
set(handles.field_labelSearch,'String','');
set(handles.pushbutton_NewSrch,'Visible','off');
set(handles.pushbutton_addSource,'Visible','off');

function [hDial] = openRunningDialog(hDisplay)
hDial = showinfowindow({'Connecting to the server ...','Running request...'},'Please wait ...',hDisplay);
%set(hDial,'CloseRequestFcn','');
t = get(hDial,'Position');
set(hDial,'Position',t);
movegui(hDial,'onscreen');



function field_labelSearch_Callback(hObject, eventdata, handles)
% hObject    handle to field_labelSearch (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of field_labelSearch as text
%        str2double(get(hObject,'String')) returns contents of field_labelSearch as a double


% --- Executes during object creation, after setting all properties.
function field_labelSearch_CreateFcn(hObject, eventdata, handles)
% hObject    handle to field_labelSearch (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function myResizeFcn(hObject,handles)
% Figure resize callback
%   Adjust object positions so that they maintain appropriate
%   proportions

if (~isempty(handles))
    figP = get(handles.figure_DASdiscovery, 'Position');
    panP = get(handles.uipanel_SearchRegistry, 'Position');
    
    %Anchor panel search to the top of the GUI
    %only changes Y of the panel
    set(handles.uipanel_SearchRegistry,'Position',[panP(1),figP(4)-10-panP(4),panP(3),panP(4)]);
    
    guidata(hObject,handles);
end




% --- Executes when uipanel_SearchRegistry is resized.
function uipanel_SearchRegistry_ResizeFcn(hObject, eventdata, handles)
% hObject    handle to uipanel_SearchRegistry (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

function drawResultsTable(handles)

posWin = get(handles.figure_DASdiscovery,'Position');
posTab = get(handles.tab,'Position');
posPanel = get(handles.uipanel_SearchRegistry,'Position');

posWin(4) = posWin(4) + posTab(4)+10; % new height
set(handles.figure_DASdiscovery,'Position',posWin);

posTab(1) = posPanel(1); %x tab
posTab(2) = posPanel(2); %y tab
myResizeFcn(handles.figure_DASdiscovery,handles); %reposition of panel


set(handles.tab,'Position',posTab);
handles.tab.setVisible(1);
set(handles.pushbutton_NewSrch,'Visible','on');
set(handles.pushbutton_addSource,'Visible','on');
movegui(handles.figure_DASdiscovery,'northeast');
drawnow;

function pushbutton_FindRegistry_CreateFcn(hObject, eventdata, handles)
[X,map] = imread('Search.png','BackgroundColor',[0.925 0.914 0.847]);
set(hObject,'CData',X);

function pushbutton_NewSrch_CreateFcn(hObject, eventdata, handles)
[X,map] = imread('Back.png','BackgroundColor',[0.925 0.914 0.847]);
set(hObject,'CData',X);

function pushbutton_addSource_CreateFcn(hObject, eventdata, handles)
[X,map] = imread('Add.png','BackgroundColor',[0.925 0.914 0.847]);
set(hObject,'CData',X);
